package me.zhengjie.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class FileUtils {
    /**
     * 压缩文件
     *
     * @param sourceFilePath 源文件路径
     * @return
     */
    public static void compressToZip(String sourceFilePath, HttpServletResponse resp) {
        File sourceFile = new File(sourceFilePath);
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(new BufferedOutputStream(resp.getOutputStream()));
            zos.setMethod(ZipOutputStream.DEFLATED);
            writeZip(sourceFile, "", zos);
            zos.flush();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
                resp.flushBuffer();
                resp.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 遍历所有文件，压缩
     *
     * @param file       源文件目录
     * @param parentPath 压缩文件目录
     * @param zos        文件流
     */
    public static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.isDirectory()) {
            //目录
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File f : files) {
                    writeZip(f, parentPath, zos);
                }
            }
        } else {
            //文件
            try {
                //指定zip文件夹
                ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(zipEntry);
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                int len = 0;
                byte[] buffer = new byte[1024 * 1024 * 10];
                while ((len = bis.read(buffer)) != -1) {
                    zos.write(buffer, 0, len);
                }
                bis.close();
                zos.flush();
                zos.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param dir
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) {
                    return false;
                }
            }
        }
        //删除空文件夹
        return dir.delete();
    }
}
